import type { RouteLocationMatched, RouteRecordNormalized } from 'vue-router/auto';
import { type RouteNamedMap } from 'vue-router/auto/routes';
import { type LabelKeyMap, getMenuItemsByRoutes } from '@/utils/router/menu';

export function useRouterMenu(routeName: keyof RouteNamedMap, labelKeyMap?: LabelKeyMap) {
  const router = useRouter();

  /** 菜单选中项 */
  const selectedKeys = ref<string[]>([]);

  /**
   * 菜单展开项
   * 页面刷新后，应当根据选中项设置该数据，但当前版本存在bug，无法重设
   * - 侧边栏收缩状态下，该数据为空，展开后，仍然保留上次展开状态，但该数据任然为空
   */
  const openKeys = ref<string[]>([]);

  /** 菜单数据项 */
  const menuItems = computed(() => {
    /** 获取指定路径名称的路由，路由必定存在 */
    const targetRoute = router.getRoutes().find(t => t.name === routeName) as RouteRecordNormalized;
    return getMenuItemsByRoutes(targetRoute.children, undefined, labelKeyMap);
  });

  onMounted(() => {
    /** 根据路由记录，设置菜单选中项 */
    const lastMatched = router.currentRoute.value.matched
      .filter(t => t.name)
      .at(-1) as RouteLocationMatched;
    // 如果指定了菜单选中项的key
    if (lastMatched.meta?.menuSelectedKey) {
      selectedKeys.value[0] = lastMatched.meta.menuSelectedKey;
    } else {
      selectedKeys.value[0] = lastMatched.name as string;
    }
  });

  return {
    menuItems,
    selectedKeys,
    openKeys,
  };
}
